<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Multi-Threaded Programming - Thread for Win32</title>
  <meta
 content="C++ Tutorial: Multi-Threaded Programming II - Part A"
 name="description" />
  <meta
 content="C++ Tutorial, Multi-Threaded Programming II - Part A, _beginthreadex(), _beginthread(), WaitForSingleObject(), WaitForMultipleObjects(), ResumeThread(), Thread for Win32"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">

<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>
<br />
<br />
<br />
<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial<br />
Multi-Threaded Programming II Part A - Native Thread for Win32</span></div>
<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>   
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II Part A - Native Thread for Win32</a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>
<br />
<img src="images/multithread2A/WalChoolSanA.png" alt="WalChoolSanA"/>
<br />
<br />
<br />
<br />

<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="mth2pa">Multi-Threaded Programming II - Part A <br />
- Native Thread for Win32</div>
<p>Microsoft Windows operating system's support for multithreaded programming is almost similar to the support provided by POSIZ threads. The differences are not in the actual functionality but the names in the API functions.</p>
<br />
<br />


<div class="subtitle_2nd" id="creatingwindowsthread">Creating Windows Threads</div>
<p>The most basic Windows applications start with a single thread. The function call we use to create a child thread is <strong>CreateThread()</strong>. The following syntax shows the parameters passed to <strong>CreateThread()</strong>.</p>
<pre>
HANDLE WINAPI CreateThread(
__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
__in SIZE_T dwStackSize,
__in LPTHREAD_START_ROUTINE lpStartAddress, 
__in_opt LPVOID lpParameter, 
__in DWORD dwCreationFlags,
__out_opt LPDWORD lpThreadId 
); 
</pre>
<p><strong>Parameters</strong></p>
<ul>
<li><strong>lpThreadAttributes </strong>[in, optional] <br />
A pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If <strong>lpThreadAttributes</strong> is NULL, the handle cannot be inherited. <br />
The <strong>lpSecurityDescriptor</strong> member of the structure specifies a security descriptor for the new thread. If <strong>lpThreadAttributes</strong> is NULL, the thread gets a default security descriptor. The ACLs in the default security descriptor for a thread come from the primary token of the creator.</li>
<li><strong>dwStackSize</strong> [in] <br />
The initial size of the stack, in bytes. The system rounds this value to the nearest page. If this parameter is zero, the new thread uses the default size for the executable. </li>
<li><strong>lpStartAddress</strong> [in] <br />
A pointer to the application-defined function to be executed by the thread. This pointer represents the starting address of the thread. </li>
<li><strong>lpParameter</strong> [in, optional] <br /> 
A pointer to a variable to be passed to the thread.</li>
<li><strong>dwCreationFlags</strong> [in] <br />
The flags that control the creation of the thread.</li>
<li><strong>lpThreadId</strong> [out, optional] <br /> 
A pointer to a variable that receives the thread identifier. If this parameter is NULL, the thread identifier is not returned. </li>
</ul>
<p>The return value from the function call is a <strong>handler</strong> for the thread, which is a different construct than the <strong>thread ID</strong>. When the call was unsuccessful, it returns 0. With the exception of the address of the function to execute, all of the parameters will take default values if they are provided the null. The following code shows how to create a child thread using the <strong>CreateThread()</strong>. The call to <strong>GetCurrentThreadId()</strong> returns an integer ID for the calling thread. It also captures the ID of the created thread. The threadID is not very useful since most functions take the thread handle as a parameter.</p>
<pre>
#include &lt;Windows.h&gt;
#include &lt;stdio.h&gt;

DWORD WINAPI mythread(__in LPVOID lpParameter)
{
	printf("Thread %d \n", GetCurrentThreadId());
	return 0;
}

int main(int argc, char* argv[])
{
	HANDLE myhandle;
	DWORD mythreadid;
	myhandle = <font color="blue">CreateThread</font>(0, 0, mythread, 0, 0, &mythreadid);
	printf("Thread %d \n", mythreadid);
	getchar();
	return 0;
}
</pre>
<p>Output is:</p>
<pre>
Thread 6784
Thread 6784
</pre>
<p>At the moment of calling <strong>CreateThread()</strong> tells the OS to make a new thread. But it does not set up the thread to work with the libraries provided by the developer environment. </p>
<p>In other words, though Windows creates the thread and returns a handle to that thread, the runtime libraries haven't set up the thread-local data structures that they need. </p>
<p>So, instead of calling <strong>CreateThread()</strong>, we should use the calls by the runtime libraries. The two recommended ways of creating a thread are the calls <strong>_beginthread()</strong> and <strong>_beginthreadex()</strong>. These two functions take different parameters: </p>
<pre>
uintptr_t _beginthread( 
   void( *start_address )( void * ),
   unsigned stack_size,
   void *arglist 
);

uintptr_t _beginthreadex( 
   void *security,
   unsigned stack_size,
   unsigned ( *start_address )( void * ),
   void *arglist,
   unsigned initflag,
   unsigned *thrdaddr 
);
</pre>
<p><strong>Parameters</strong></p>
<ul>
<li><strong> start_address </strong><br />
Start address of a routine that begins execution of a new thread. For <strong> _beginthread</strong>, the calling convention is either __cdecl or __clrcall; for <strong>_beginthreadex</strong>, it is either __stdcall or __clrcall.<br />
<li><strong> stack_size</strong><br />
Stack size for a new thread or 0. </li>
<li><strong> arglist </strong><br />
Argument list to be passed to a new thread or NULL.</li>
<li><strong> security </strong><br />
Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If NULL, the handle cannot be inherited.</li>
<li><strong> initflag </strong><br />
Initial state of a new thread (0 for running or CREATE_SUSPENDED for suspended); use ResumeThread to execute the thread.</li>
<li><strong> thrdaddr </strong><br />
Points to a 32-bit variable that receives the thread identifier. Might be NULL, in which case it is not used.</li>
</ul>
<p>There is another difference between these two functions other than the parameters they take. A thread created by <strong> _beginthread()</strong> will close the handle to the thread when the thread exits while the handle returned by <strong>_beginthreadex()</strong> will have to be explicitly closed by calling <strong>CloseHandle()</strong>, which is a similar to the detached thread in POSIX.</p>
<p>As we see in the description of the two functions above, they are also differ by the type of function that the thread execute: <strong> _beginthread()</strong> is a <strong>void</strong> function and uses the default calling convention <strong>__cdecl</strong>, while <strong>_beginthreadex()</strong> returns an unsigned <strong>int</strong> and uses the <strong>__stdcall</strong> calling convention.</p>
<p>The <strong> _beginthread()</strong> and  <strong> _beginthreadex()</strong> functions return handles to the newly created threads. But the actual return type of the function call is <strong>uintptr_t</strong> which has to be type cast to a <strong>HANDLE</strong> before it can be used in function calls that expect an object handle.</p>
<p>The following example creates threads using the three different ways:</p>
<pre>
#include &lt;Windows.h&gt;
#include &lt;process.h&gt;
#include &lt;stdio.h&gt;

DWORD WINAPI mythreadA(__in LPVOID lpParameter)
{
	printf("CreateThread %d \n", GetCurrentThreadId());
	return 0;
}

unsigned int __stdcall mythreadB(void* data)
{
	printf("_beginthreadex %d \n", GetCurrentThreadId());
	return 0;
}

void mythreadC(void* data)
{
	printf("_beginthread %d \n", GetCurrentThreadId());
}

int main(int argc, char* argv[])
{
	HANDLE myhandleA, myhandleB, myhandleC;

	myhandleA = <font color="blue">CreateThread</font>(0, 0, mythreadA, 0, 0, 0);

	myhandleB = (HANDLE)<font color="blue">_beginthreadex</font>(0, 0, &mythreadB, 0, 0, 0);
	<font color="blue">WaitForSingleObject</font>(myhandleB, INFINITE);


	myhandleC = (HANDLE)<font color="blue">_beginthread</font>(&mythreadC, 0, 0);
	getchar();

	return 0;
}
</pre>
<p>Output is:</p>
<pre>
_beginthreadex 5256
CreateThread 5924
_beginthread 4292
</pre>
<p>The call to <strong>WaitForSingleObject()</strong> waits for an object to signal its readiness. In other words, the routine is passes the handle to a thread and waits for that thread to terminate.</p>
<p>Calling <strong>_beginthread()</strong> looks more convenient because it takes fewer parameters and clean up the handle after the thread exits, however, it is better to use <strong>_beginthreadex()</strong>.</p>
<p>Calling <strong>_beginthreadex()</strong> avoids a difficulty with <strong>_beginthread()</strong>. If the thread terminates, the handle returned by the call to <strong>_beginthread()</strong> will be invalid or even reused. Therefore, it is impossible to query the status of the thread or even be confident that the handle to the thread is a handle to the same thread to which is originally pointed. The following example demonstrates this issue:</p>
<pre>
#include &lt;Windows.h&gt;
#include &lt;process.h&gt;
#include &lt;stdio.h&gt;

void mythreadA(void* data)
{
	printf("mythreadA %d \n", GetCurrentThreadId());
}

void mythreadB(void* data)
{
	volatile int i;

	// Most compiler won't eliminate the loop
	// since i is volatile
	for (i = 0; i < 100000; i++) {}

	printf("mythreadB %d \n", GetCurrentThreadId());
}

int main(int argc, char* argv[])
{
	HANDLE myhandleA, myhandleB;

	myhandleA = (HANDLE)<font color="blue">_beginthread</font>(&mythreadA, 0, 0);
	myhandleB = (HANDLE)<font color="blue">_beginthread</font>(&mythreadB, 0, 0);
	<font color="blue">WaitForSingleObject</font>(myhandleA, INFINITE);
	<font color="blue">WaitForSingleObject</font>(myhandleB, INFINITE);

	return 0;
}
</pre>
<p>Output is:</p>
<pre>
mythreadA 5912
mythreadB 3092
</pre>
<p>The <strong>mythreadA()</strong> terminates quickly and may have already terminated by the time that the main thread reaches the call to create the second thread. If the first thread has terminated, the handle to the first thread may be reused as the handle to the second thread. Queries using the handle of the first thread might succeed, but they will work on the wrong thread. The calls to <strong>WaitForSingleObject()</strong> may not be using a correct or valid handle for either of the threads depending on the completion time of the threads. Though it is not clear from the output, still, there is a potential for things not going to work as we expect.</p>
<p>The following example for using <strong>_beginthreadex()</strong>  is equivalent to the previous code. Thread created by <strong>_beginthreadex()</strong> need to be cleaned up by calling <strong>CloseHandle()</strong>. So, the calls to <strong>WaitForSingleObject()</strong> are certain to get the correct handles:</p>
<pre>
#include &lt;Windows.h&gt;
#include &lt;process.h&gt;

unsigned int __stdcall mythreadA(void* data) 
{
	return 0;
}

unsigned int __stdcall  mythreadB(void* data)
{
	volatile int i;

	// Most compiler won't eliminate the loop
	// since i is volatile
	for (i = 0; i < 100000; i++) {}

	return 0;
}

int main(int argc, char* argv[])
{
	HANDLE myhandleA, myhandleB;

	myhandleA = (HANDLE)_beginthreadex(0, 0, &mythreadA, 0, 0, 0);
	myhandleB = (HANDLE)_beginthreadex(0, 0, &mythreadB, 0, 0, 0);
	WaitForSingleObject(myhandleA, INFINITE);
	WaitForSingleObject(myhandleB, INFINITE);
	<font color="blue">CloseHandle</font>(myhandleA);
	<font color="blue">CloseHandle</font>(myhandleB);

	return 0;
}
</pre>
<p>And the output:</p>
<pre>
mythreadA 5860
mythreadB 5312
</pre>
<br />
<br />


<div class="subtitle_2nd" id="terminatingwindowsthread">Terminating Threads</div>
<p>There are several ways to make a thread to terminate. But the recommended way is for the thread to exit the function that it was instructed to run. In the following example, the thread will print out its ID and then exit:</p>
<pre>
DWORD WINAPI mythreadA(__in LPVOID lpParameter)
{
	printf("CreateThread %d \n", GetCurrentThreadId());
	return 0;
}
</pre>
<p>It is also possible to make threads to terminate using the <strong>ExitThread()</strong> or <strong>TerminateThread()</strong>. But these function calls are not recommended since they may leave the application in an unspecified state. The thread does not get the chance to release any held mutexes or free any other allocated resources. They also don't give the run-time libraries the opportunity to clean up any resources that they have allocated for the thread.</p>
<p>As long as care is taken to ensure that resources the thread has acquired are appropriately freed a thread may terminate with a call to <strong>_endthread()</strong> or <strong>_endthreadex()</strong>. This call needs to match the call that was used to create the thread. If the thread exits with a call to <strong>_endthreadex()</strong>, the handle to the thread still needs to be closed by another thread calling <strong>cloaseHandle()</strong>.</p>
<p>For a fork-join type model, there will be a master thread that creates multiple worker threads and then waits for the worker threads to exit. There are two routines that the master thread can use to wait for the worker to complete: <strong>WaitForSingleObject()</strong> or <strong>WaitForMultipleObjects()</strong>. These two functions will wait either for the completion of a single thread or for the completion of an array of threads. The routines take the handle of the thread as a parameter together with a timeout value that indicates how long the master thread should wait for the worker thread to complete. Usually, the value <strong>INFINITE</strong> will be appropriate. The following code demonstrates the code necessary to wait for a single thread to complete:</p>
<pre>
#include &lt;Windows.h&gt;
#include &lt;process.h&gt;
#include &lt;stdio.h&gt;

unsigned int __stdcall mythread(void* data) 
{
	printf("Thread %d\n", GetCurrentThreadId());
	return 0;
}

int main(int argc, char* argv[])
{
	HANDLE myhandle[2];

	myhandle[0] = (HANDLE)_beginthreadex(0, 0, &mythread, 0, 0, 0);
	myhandle[1] = (HANDLE)_beginthreadex(0, 0, &mythread, 0, 0, 0);
	WaitForSingleObject(myhandle[0], INFINITE);
	WaitForSingleObject(myhandle[1], INFINITE);
	CloseHandle(myhandle[0]);
	CloseHandle(myhandle[1]);
	getchar();

	return 0;
}
</pre>
<p>Output from the run is:</p>
<pre>
Thread 4360
Thread 1368
</pre>
<br />
<p>The following code is equivalent to the previous one. But this example is using <strong>WaitForMultipleObjects()</strong>. <p>
<ol>
	<li>The first parameter to the function call is the number of threads that are to be waited for. </li>
	<li>The second parameter is a pointer to the array of handles to these threads. </li>
	<li>The third parameter is a boolean. If true, it indicates that the function should return when all the threads are complete. If false, it indicates the function should return on the completion of the first worker thread.</li>
	<li>The last parameter is the length of time that the master thread should wait before returning anyway.</li>
</ol>
<pre>
#include &lt;Windows.h&gt;
#include &lt;process.h&gt;
#include &lt;stdio.h&gt;

unsigned int __stdcall mythread(void* data) 
{
	printf("Thread %d\n", GetCurrentThreadId());
	return 0;
}

int main(int argc, char* argv[])
{
	HANDLE myhandle[2];

	myhandle[0] = (HANDLE)_beginthreadex(0, 0, &mythread, 0, 0, 0);
	myhandle[1] = (HANDLE)_beginthreadex(0, 0, &mythread, 0, 0, 0);

	<font color="blue">WaitForMultipleObjects(2, myhandle, true, INFINITE);</font>

	CloseHandle(myhandle[0]);
	CloseHandle(myhandle[1]);
	getchar();

	return 0;
}
</pre>
<p>Output is:</p>
<pre>
Thread 4712
Thread 4244
</pre>
<p>Even after a thread created by calling <strong>_beginthreadex</strong> has exited, it will continue to hold resources. These resources need to be freed by calling the <strong>CloseHandle()</strong> function on the handle to the thread. The following example demonstrates the complete sequence of creating a thread, waiting for it to complete, and then freeing its resources:</p>
<pre>
#include &lt;Windows.h&gt;
#include &lt;process.h&gt;
#include &lt;stdio.h&gt;

unsigned int __stdcall mythread(void* data) 
{
	printf("Thread %d\n", GetCurrentThreadId());
	return 0;
}

int main(int argc, char* argv[])
{
	HANDLE myhandle;

	myhandle = (HANDLE)_beginthreadex(0, 0, &mythread, 0, 0, 0);

	WaitForSingleObject(myhandle, INFINITE);

	CloseHandle(myhandle);

	return 0;
}
</pre>
<p>Output is:</p>
<pre>
Thread 4272
</pre>
<br />
<br />


<div class="subtitle_2nd" id="resumethread">Resuming Suspended Threads</div>
<p>A <strong>suspended</strong> thread is the one that is not currently running. Threads can be created in the suspended state and then started later. If a thread is in the suspended state, then the call to start the thread executing is <strong>ResumeThread()</strong>. It takes the handle of the thread as a parameter. </p>
<p>There is a <strong>SuspendThread()</strong> call that will cause a running thread to be suspended. This call is expected to be used only by tools such as debugger. Suspending a running thread may lead to problems if the thread currently holds resources such as mutexes. </p>
<p>The following code demonstrates the creation of a suspended thread and then calling <strong>ResumeThread()</strong> on that thread. The code uses a call to <strong>getchar()</strong>, which waits for the enter key to be pressed, to separate the creation of the thread from the act of resuming thread:</p>
<pre>
#include &lt;Windows.h&gt;
#include &lt;process.h&gt;
#include &lt;stdio.h&gt;

unsigned int __stdcall mythread(void* data) 
{
	printf("Thread %d\n", GetCurrentThreadId());
	return 0;
}

int main(int argc, char* argv[])
{
	HANDLE myhandle;

	myhandle = (HANDLE)_beginthreadex(0, 0, &mythread, 0, <font color="blue">CREATE_SUSPENDED</font>, 0);
	getchar();
	<font color="blue">ResumeThread(myhandle);</font>
	getchar();
	WaitForSingleObject(myhandle, INFINITE);
	CloseHandle(myhandle);

	return 0;
}
</pre>
<p>Output we get after we hit the return key:</p>
<pre>
(hit Return key)
Thread 4580
</pre>
<p>The suspended state of the thread is handled as a counter, so multiple calls to <strong>SuspendThread()</strong> need to be matched with multiple calls to <strong>ResumeThread()</strong>.</p>
<br />
<br />


<div class="subtitle_2nd" id="kernel">Kernel Resources</div>
<p>Many of the Windows API functions return <strong>handles</strong>. As we saw from the earlier discussion of type casting, these are really just unsigned integers. However, they have a particular purpose. Windows API calls that return handles have actually caused a resource to be created within the <strong>kernel space</strong>. The handle is just an index for that resource. When the application has finished with the resource, the call to <strong>CloseHandle()</strong> enables the kernel to free the associated kernel space resources.</p>
<p><strong>Resources with handles can be shared between processes</strong>. Once a resource exists, other processes can open a handle to that resource or duplicate an existing handle to the resource. It is important to know that the handle of a kernel resource makes sense only within the context of the process that has access to the resource. Passing the value of the handle to another process does not enable the other process to get access to the resource. The kernel need to enable access to the resource and provide a new handle for the existing resource in the new process.</p>
<p>Some functions do not return a handle. For these functions, there is no associated kernel resource. So, it is not necessary to call <strong>CloseHandle()</strong> once the resource is no longer needed.</p>



<br />
<img src="images/multithread2A/WalChoolSanB.png" alt="WalChoolSanB"/>
<br />
<br />

<br /><br />
<div class="subtitle_2nd" id="FullList">List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II Part A - Native Thread for Win32</a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>

<br /><br />


<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2010 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
